//
//  RootViewController.swift
//  Owner
//
//  Created by HelloKitty on 21/8/2020.
//  Copyright © 2020 HelloKitty. All rights reserved.
//

import UIKit
import JXSegmentedView
import Reachability

class RootViewController: BaseViewController {
    
    // 导航条高度
    let NAVBAR_HEIGHT: CGFloat = 44
    // 状态栏高度
    let STATUSBAR_HEIGHT: CGFloat = appStatusBarHeight()
    // 整体导航栏高度
    let FULLNAVBAR_HEIGHT = NAVBAR_HEIGHT + STATUSBAR_HEIGHT
    
    //获取状态栏高度，用安全区域的顶部距离屏幕顶部高度
    //12 mini 特殊 状态栏 44 导航栏 44 ，但是两者相距 6
    func appStatusBarHeight() -> CGFloat {
        //根据安全区域
        if let safeAreaTop = UIApplication.shared.keyWindow?.safeAreaInsets.top {
            return safeAreaTop
        }else {
            return 0.0
        }
    }
    
    //跳转到推荐
    var toIdx0: Bool = false
    
    let reachability = try! Reachability()
    // 网络状态
    private var netConnect: Bool = true
    
    var controllers = [CommunityParentController]()
    //
    lazy var segmentedDataSource: JXSegmentedTitleDataSource = {
        let dataSource = JXSegmentedTitleDataSource()
        dataSource.titles = ["推荐", "能社区", "资讯", "活动"]
        dataSource.titleNormalColor = "#222222".color()
        dataSource.titleNormalFont = UIFont.systemFont(ofSize: 14)
        dataSource.titleSelectedColor = "#222222".color()
        dataSource.titleSelectedFont = UIFont.systemFont(ofSize: 16, weight: .semibold)
        return dataSource
    }()
    
    lazy var contentView: UIScrollView = {
        let view = UIScrollView(frame: self.view.bounds)
        view.isPagingEnabled = true
        view.showsVerticalScrollIndicator = false
        view.showsHorizontalScrollIndicator = false
        view.scrollsToTop = false
        view.bounces = false
        self.view.addSubview(view)
        return view
    }()
    
    //
    lazy var segmentedView: JXSegmentedView = {
        let segmentedView = JXSegmentedView()
        return segmentedView
    }()
    
    private lazy var addTrend: UIButton = {
        let button = UIButton(type: .custom)
        self.view.addSubview(button)
        button.setImage(BNFestiveSkinsManager.manager.festiveSkinLocation16Imge, for: .normal)
        button.snp.makeConstraints { (make) in
            make.bottom.equalToSuperview().offset(-TABBAR_HEIGHT-11)
            make.right.equalToSuperview().offset(0)
            make.width.equalTo(72)
            make.height.equalTo(75)
        }
    
        return button
    }()
    
    // MARK: - =====================cycle====================
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        
        if toIdx0 {
            toIdx0 = false
            self.segmentedView.selectItemAt(index: 0)
        }
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        //单个控制器设置背景图
        self.navigation.bar.setBackgroundImage(BNFestiveSkinsManager.manager.festiveSkinLocation01Imge, for: .default)
        navigation.item.titleView = UIImageView(image: BNFestiveSkinsManager.manager.festiveSkinLocation02Imge)
        //
        navigation.item.rightBarButtonItem = UIBarButtonItem.init(image: UIImage.init(named: "share")?.withRenderingMode(.alwaysOriginal), style: .plain, target: self, action: #selector(self.shareAction))
        //刷新数据
        reloadData()
        //
        //        Global.getUserInfo()
        //全局通知
        _ = NotificationCenter.default.rx
            .notification(.kNotificationMain)
            .takeUntil(self.rx.deallocated)
            .subscribe(onNext: { [weak self](_) in
                self?.reloadData()
            })
        
        self.joinCarClubFlag()
        //发布后返回通知
        reloadDynamicState()
        //网络状态
        netStatus()
        //显示首页指引
        showNewFeature(["mainnewfeature-0","mainnewfeature-1","mainnewfeature-2"])
        
        //监听更新节日皮肤更新通知
        addFestiveSkinUpdateNotification()
    }
    
    //微信分享
    @objc func shareAction(){
        let cards =  [[
            "title": "微信",
            "icon": "wechat2",
            "handler": "friend"
        ],[
            "title": "举报",
            "icon": "report",
            "handler": "report"
        ]]
        
        let cancelBtn = [
            "title": "取消",
            "type": "default"
        ]
        let mmShareSheet = MMShareSheet.init(title: "", items: cards, duration: nil, cancelBtn: cancelBtn)
        mmShareSheet.callBack = { (handler) ->() in
            Log.info(handler)
            self.sendText(text: handler)
        }
        mmShareSheet.present()
        
    }//分享文本
    func sendText(text:String){
        if (text == "friend") {
            //小程序的路径
            let path = "views/pages/index/community/index"
            //小程序的环境
            var type :WXMiniProgramType = WXMiniProgramType(rawValue: 2)!
            if ServerManager.shared.config == .release {
                type = WXMiniProgramType(rawValue: 0)!
            }
            //web分享参数 
            let webPara:WebpageSharePara = WebpageSharePara.init(webpageUrl: OFFICIAL_WEBSITE as NSString, title: "欢迎到能行社区跟我互动~", description: "宝能汽车", thumbImag: UIImage.init())
            //小程序分享参数
            let miniPara:MiniProgramSharePara = MiniProgramSharePara.init(webpageUrl: OFFICIAL_WEBSITE as NSString, userName: MINI_ORIGINALID_ENUM.BQT.rawValue as NSString, path: path as NSString, hdImageData: (UIImage.init(named: "shareMiniProg")? .jpegData(compressionQuality: 1.0)!)! as NSData, withShareTicket: false, miniprogramType: type)
            //分享
            SharingWeixinTool.sharedInstance.shareMiniProgram(webPara: webPara, miniPara: miniPara, to: WXSceneSession)
        }else if(text == "report"){
            //客服
            makePhoneCall(phoneNumber: CONSUMER_HOTLINE)
        }else{
            //取消
        }
    }
    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        
        self.contentView.contentSize = CGSize(width: SCREEN_WIDTH*CGFloat(segmentedDataSource.dataSource.count), height: SCREEN_HEIGHT)
        //
        for (index, controller) in controllers.enumerated() {
            controller.view.frame = CGRect(x: SCREEN_WIDTH*CGFloat(index), y: 0, width: SCREEN_WIDTH, height: SCREEN_HEIGHT)
        }
    }
    
    // MARK: - =====================添加view====================
    override func addSubViews() {
        //
        self.segmentedView.contentScrollView = self.contentView
        //
        self.segmentedView.dataSource = self.segmentedDataSource
        //
        let indicator = JXSegmentedIndicatorLineView()
        indicator.indicatorWidth = 16
        indicator.verticalOffset = 5
        if BNFestiveSkinsManager.manager.festiveSkinLocation03Imge != nil {
            indicator.indicatorColor = .white
            let indiImage:UIImage  = BNFestiveSkinsManager.manager.festiveSkinLocation03Imge!
            let indiImageView = UIImageView.init(image: indiImage)
            indiImageView.frame = CGRect.init(x:(indicator.width - indiImage.size.width) / 4.0 ,y:(indicator.height - indiImage.size.height) ,width: indiImage.size.width, height: indiImage.size.height)
            indicator.addSubview(indiImageView)
        }else{
            indicator.indicatorColor = Theme.colorAccent
        }
       
        //
        self.segmentedView.indicators = [indicator]
        //
        self.segmentedView.delegate = self
        
        self.view.addSubview(segmentedView)
        segmentedView.backgroundColor = .white
        segmentedView.snp.makeConstraints { (make) in
            make.left.right.equalToSuperview()
            make.top.equalTo(navigation.bar.snp.bottom)
            make.height.equalTo(45)
        }
        
        self.addTrend.rx.tap
            .subscribe(onNext: { [weak self] in
                self?.isLogin({ _ in
                    
                    let controller = NewReleaseStateVC.init(contentId: 0, topicId: 0, topicName: "", isSynchronizeCarClub: false, dynamicStateType: .release, contentStateType: .image)
                    self?.navigationController?.pushViewController(controller, animated: true)

                })
            }).disposed(by: disposeBag)
    }
    //动态发布后的刷新
    func reloadDynamicState(){
        // 刷新通知
        _ = NotificationCenter.default.rx
            .notification(.kNotificationDynamicResult)
            .takeUntil(self.rx.deallocated)
            .subscribe(onNext: { [weak self]( notification ) in
                let userInfo = notification.userInfo as! [String: AnyObject]
                let value = userInfo["action"]
                if(value as! DynamicResult == DynamicResult.release){
                    //发布成功后回调
                    self?.segmentedView.defaultSelectedIndex = 1
                    self?.segmentedView.reloadData()
                    let index = self!.segmentedView.selectedIndex
                    self!.controllers[index].updatePage()
                }
            })
    }
    //刷新数据
    @objc func reloadData() {
        
        segmentedView.defaultSelectedIndex = 0
        segmentedView.reloadData()
        //
        for item in self.controllers {
            item.view.removeFromSuperview()
        }
        controllers.removeAll()
        //
        for index in 0..<self.segmentedDataSource.titles.count {
            if index == 0 {
                let controller = RecommendViewController()
                controller.moduleId = index + 2
                controller.naviController = navigationController
                self.contentView.addSubview(controller.view)
                controllers.append(controller)
            } else if index == 2 {
                let controller = InformationController()
                controller.moduleId = index + 2
                controller.naviController = navigationController
                self.contentView.addSubview(controller.view)
                controllers.append(controller)
            } else if index == 3 {
                let controller = ActivityViewController()
                controller.moduleId = index + 2
                controller.naviController = navigationController
                self.contentView.addSubview(controller.view)
                controllers.append(controller)
            } else {
                let controller = CommunityViewController()
                controller.moduleId = index + 2
                controller.naviController = navigationController
                self.contentView.addSubview(controller.view)
                controllers.append(controller)
            }
        }
        self.view.setNeedsLayout()
        //
        controllers.first?.loadDataForFirst()
    }
    
    // MARK: - =====================监听网络状态====================
    func netStatus() {
        reachability.whenReachable = { reach in
            if reach.connection == .wifi || reach.connection == .cellular {
                if self.netConnect == false {
                    self.reloadData()
                    self.netConnect = true
                }
            }
        }
        
        reachability.whenUnreachable = { reach in
            self.netConnect = false
        }
        
        do {
            try reachability.startNotifier()
        } catch {
            Log.info("Unable to start notifier")
        }
    }
    
    // MARK: 更新节日皮肤
    private func addFestiveSkinUpdateNotification() {
        
        _ = NotificationCenter.default.rx
            .notification(.kNotificationUpdateFestiveSkin)
            .takeUntil(self.rx.deallocated)
            .subscribe(onNext: { [weak self]( notification ) in
                
                self?.navigation.bar.setBackgroundImage(BNFestiveSkinsManager.manager.festiveSkinLocation01Imge, for: .default)
                self?.navigation.item.titleView = UIImageView(image: BNFestiveSkinsManager.manager.festiveSkinLocation02Imge)
                self?.addTrend.setImage(BNFestiveSkinsManager.manager.festiveSkinLocation16Imge, for: .normal)
                
                if let indicators = self?.segmentedView.indicators, let indicator = indicators.last, let indicatorView = indicator as? JXSegmentedIndicatorLineView {

                    if BNFestiveSkinsManager.manager.festiveSkinLocation03Imge != nil {
                        
                        for indicatorSubview in indicatorView.subviews {
                            indicatorSubview.removeFromSuperview()
                        }
                        
                        indicatorView.indicatorColor = .white
                        let indiImage:UIImage  = BNFestiveSkinsManager.manager.festiveSkinLocation03Imge!
                        let indiImageView = UIImageView.init(image: indiImage)
                        indiImageView.frame = CGRect.init(x:(indicator.width - indiImage.size.width) / 4.0 ,y:(indicator.height - indiImage.size.height) ,width: indiImage.size.width, height: indiImage.size.height)
                        indicator.addSubview(indiImageView)

                    }else{

                        indicatorView.indicatorColor = Theme.colorAccent

                        for indicatorSubview in indicatorView.subviews {
                            indicatorSubview.removeFromSuperview()
                        }
                    }
                    
                    self?.segmentedView.reloadData()
                }
                
            })
    }
    
    // MARK: - =====================获取joinCarClubFlag====================
    private func joinCarClubFlag() {
        Service.UserProvider().request(.getCarClubHomePage) { (result) in
            switch result {
            case .success(let response):
                if let model = try? response.map(CarClubMainModel.self) {
                    if model.status == 0 {
                        Global.joinCarClubFlag = model.data?.joinCarClubFlag ?? false
                    }
                }
            case .failure(_): break
            }
        }
    }
}

extension MainViewController: JXSegmentedViewDelegate {
    func segmentedView(_ segmentedView: JXSegmentedView, didSelectedItemAt index: Int) {
        self.controllers[index].loadDataForFirst()
    }
}
